package cn.myjerry.collection;

import java.util.Arrays;

/**
 * 自定义ArrayList容器
 * @author Jerry
 *
 */

public class SxtArrayList {
	
	private Object[] elementData;
	
	private int size;
	
	public SxtArrayList() {
		this(10);
	}
	
	public SxtArrayList(int initialCapacity) {
		this.elementData = new Object[initialCapacity];
	}
	
	public int size() {
		return size;
	}
	
	public boolean isEmpty() {
		return size == 0;
	}
	
	public boolean add(Object o) {
		if(size >= elementData.length-1) {
			Object[] newArray = new Object[size*2+1];
			System.arraycopy(elementData, 0, newArray, 0, elementData.length);
			elementData = newArray;
		}
		elementData[size++] = o;
		return true;
	}
	
	public boolean add(int index, Object o) {
		rangeCheck(index);
		if(size >= elementData.length-1) {
			Object[] newArray = new Object[size*2+1];
			System.arraycopy(elementData, 0, newArray, 0, elementData.length);
			elementData = newArray;
		}
		System.arraycopy(elementData, index, elementData, index+1, size-index);
		elementData[index] = o;
		size++;
		return true;
	}
	
	public Object get(int index) {
		rangeCheck(index);
		return elementData[index];
	}
	
	public Object remove(int index) {
		rangeCheck(index);
		
		Object oldVal = elementData[index];
		
		int numMoved = size - index - 1;
		if(numMoved > 0)
			System.arraycopy(elementData, index+1, elementData, index, numMoved);
		elementData[--size] = null;
		return oldVal;
	}
	
	public Object remove(Object o) {
		Object b = null;
		for(int i=0;i<size;i++) {
			if(elementData[i].equals(o)) {
				b = remove(i);
			}
		}
		return b;
	}
	
	public boolean set(int index, Object o) {
		rangeCheck(index);
		elementData[index] = o;
		return true;
	}
	
	public void rangeCheck(int index) {
		if(index<0 || index >= size) {
			try {
				throw new Exception();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "SxtArrayList [elementData=" + Arrays.toString(elementData) + "]";
	}

	public static void main(String[] args) {
		SxtArrayList list = new SxtArrayList(3);

		list.add(123);
		list.add(456);
		list.add(789);
		list.add(295);
		list.add(345);

		System.out.println(list.get(2));
		System.out.println(list.toString());
		System.out.println(list.remove(new Integer(789)));
		System.out.println(list.get(2));
		System.out.println(list.toString());
	}
}